package com.dm.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.protocol.RequestContent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * PRE拦截器
 * @自定义内容：
 */

@Component
@RefreshScope
public class PreFilter extends ZuulFilter {

    @Value("${token}")
    private boolean token;
    /**
     * 过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器，优先级，可以是负数
     * （多个同类型的时候设置优先级，数值越低，优先级越高）
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前这个过滤器是否要参与网关的处理，ture参与
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 实际业务处理
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //多个过滤器也是通过这个对象传递信息
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
       /* String key = request.getParameter("key");
        System.out.println(key + " access filter 1");
        ctx.set("thirdfilter", true);
        if ("1".equals(key)) {
            ctx.setSendZuulResponse(false);
        } else if ("".equals(key)) {
            ctx.set("thirdfilter", false);
        }*/
        /* String token = request.getHeader("token");
         if(token==null||token.equals("")){
             //传递到下一个拦截器，失败的状态
            ctx.setSendZuulResponse(false);
            //返回给客户端的状态
            ctx.setResponseStatusCode(401);
            //返回给客户端的信息
            ctx.setResponseBody("{\"code\":401,\"msg\":\"请先登入\"}");
             return "失败";
         }
        return "成功";*/
        System.out.println("================="+token+"===========================");
        if (token) {
            String token = request.getHeader("token");
            if (token == null || token.equals("")) {
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(401);
                ctx.setResponseBody("{\"msg\":\"401, access without permission , pls login first.\"}");
                return "access denied";
            }
        }
        return "pass";
    }
}
